extends Node

# --- 配置参数 ---
@export var type_delay := 0.05       # 打字机效果延迟

# --- 变量定义 ---
var api_key = ""
var conversation = [
	{
		"role": "system",
		"content": """#### 定位
- 桌面智能助手
- 主要任务：进行知识问答和生活建议

#### 能力
- 情绪识别表达：[emotion=X] (X 为 happy/confused/focused/boring/backoff)
- 回答精简：2-3 句话
- 趣味类比：每次回答包含有趣的比喻
- 单表情表达：每个回答用 1 个贴切 emoji

#### 使用方式
- 用户输入问题，助手根据上下文给出回应
- 回答以 [emotion=X] 开头，紧接核心答案，辅以类比描述，加入 1 个相关 emoji
- 禁止输出多个 emotion 标签，不能使用多个 emoji
"""
	}
]

# --- 初始化 ---
func _ready():
	_load_api_key()
	$WeatherButton.pressed.connect(_on_WeatherButton_pressed)
	$SendButton.pressed.connect(_on_send_button_pressed)
	$UserInput.text_submitted.connect(_on_send_enter_pressed)
	$AskQuestion.request_completed.connect(_on_ask_question_completed)

# --- 加载 API 密钥 ---
func _load_api_key():
	var config = ConfigFile.new()
	var err = config.load("res://config/secret.cfg")
	if err != OK:
		push_error("❌ 无法加载 API 密钥配置文件！请确保 config/secret.cfg 存在。")
		return
	api_key = config.get_value("deepseek", "api_key", "")
	if api_key == "":
		push_error("❌ 配置文件中未找到 api_key！")

# --- UI 事件处理 ---
func _on_WeatherButton_pressed():
	conversation.append({"role": "user", "content": "What's the weather?"})
	call_api($AskQuestion)

func _on_send_button_pressed():
	var content = $UserInput.text.strip_edges()
	if content != "":
		conversation.append({"role": "user", "content": content})
		$UserInput.text = ""
		call_api($AskQuestion)

func _on_send_enter_pressed(new_text):
	_on_send_button_pressed()

# --- API 请求 ---
func call_api(request_node):
	var url = "https://api.deepseek.com/chat/completions"
	var headers = [
		"Content-Type: application/json",
		"Authorization: Bearer " + api_key
	]
	var data = {
		"model": "deepseek-chat",
		"messages": conversation,
		"stream": false
	}
	var body = JSON.stringify(data)
	request_node.request(url, headers, HTTPClient.METHOD_POST, body)

# --- 处理 API 回应 ---
func _on_ask_question_completed(result, response_code, headers, body):
	if result == HTTPRequest.RESULT_SUCCESS and response_code == 200:
		var json = JSON.new()
		var err = json.parse(body.get_string_from_utf8())
		if err == OK:
			var resp = json.data
			var assistant_msg = resp["choices"][0]["message"]["content"]
			
			# 提取情绪与纯文本
			var emotion_result = extract_emotion(assistant_msg)
			var emotion = emotion_result[0]
			var response_text = emotion_result[1]
			
			# 播放情绪动画
			if emotion != "":
				$emotion_sprite.play(emotion)
			
			# 显示回答（打字机效果）
			display_response(response_text)
			
			# 保存到对话历史
			conversation.append({"role": "assistant", "content": assistant_msg})
		else:
			push_error("JSON 解析错误: " + json.get_error_message())
	else:
		push_error("HTTP 请求失败，结果：" + str(result) + "，响应码：" + str(response_code))

# --- 工具方法：提取情绪标签和文本 ---
func extract_emotion(text: String) -> Array:
	var emotion = ""
	var content = text

	var regex := RegEx.new()
	regex.compile("\\[emotion=(\\w+)\\]\\n?")
	var result = regex.search(text)

	if result:
		emotion = result.get_string(1)
		content = text.replace(result.get_string(0), "")
	
	return [emotion, content]

# --- 打字机效果文本输出 ---
func display_response(text: String, delay: float = type_delay, clear: bool = true) -> void:
	if clear:
		$Label.text = ""
	for c in text:
		$Label.text += c
		await get_tree().create_timer(delay).timeout
